<script setup>
import {  getClusterListHandler } from '../../api/cluster.js'
import {getNamespaceListHandler as getListHandler ,createNamespaceHandler as createItem ,deleteNamespaceHandler as deleteItem} from "../../api/namespace.js"
import {onBeforeMount, reactive, toRefs, ref ,computed } from "vue";
import Edit from "./Edit.vue";
import Detail from "./Detail.vue";
import {useRoute} from "vue-router";
import {ElMessage} from "element-plus";
import ClusterNamespaceSelector from "../components/ClusterNamespaceSelector.vue";


// loading 为true是 是加载状态，在数据加载成功后，把 loading.value设置成false 停止转圈

const  data = reactive({
  items: [],
  clusterList: [],
  clusterId: "",
  editItems: {},
  editName: "",
  detailItem: {},
  detailName: "",
  createName: "",
  deleteName: "",
  deleteNameConfirm: "",
})


const route = useRoute()
const editdialog =ref(false)
const detailDialog =ref(false)
const createNamespaceDialog =ref(false)
const deleteNamespaceDialog =ref(false)
const loading = ref(true)
const search = ref('')

// 获取集群列表
// 使用api/user.js中封装好的方法 axios 获取后端接口数据
const getList = (id)=>{
  loading.value =true
  editdialog.value = false
  console.log("集群列表中打印response")
  getListHandler(id).then((response)=>{
    console.log("集群列表中打印response",response.data.data.list)
    data.items = response.data.data.items
    console.log("打印items",data.items)
    loading.value =false
  })
}


// 编辑
const edit=(row)=>{
  loading.value=true
  console.log("编辑namespace:",row)
  data.editItems = row
  data.editName = row.metadata.name
  console.log("编辑的节点data.editItems:",data.editItems)
  editdialog.value = true   // 再点击设置按钮时 设置为true
  loading.value=false
}
// 点击集群id事件 展示数据的详细信息
const detail = (row) => {
  data.detailItem = row
  data.detailName = row.metadata.name
  detailDialog.value=true
}
// 删除
const deleteNamespace = (row)=>{
  loading.value=true
  data.deleteName = row.metadata.name
  deleteNamespaceDialog.value=true
}

// submitDeleteName
const submitDeleteName= ()=>{

  console.log("删除namespace:",data.deleteName)
  if (data.deleteName !== data.deleteNameConfirm){
    ElMessage({
      message: "删除失败：确认删除的名称不正确",
      type: 'warning',
    })
    return
  }
  // 调用创建接口创建资源
  deleteItem(data.clusterId,data.deleteName).then((response)=>{
    ElMessage({
      message: response.data.message,
      type: 'success',
    })
    getList(data.clusterId)
    deleteNamespaceDialog.value=false
    data.deleteName = ""
  })
}
// 异步执行转为同步 前面执行完执行后面
const getClusterList = async ()=>{
  await getClusterListHandler().then((res)=>{
    console.log("打印获取集群列表",res)
    data.clusterList = res.data.data.items
    console.log("打印获取集群列表data.clusterList",data.clusterList)
  })
}

// 点击创建按钮触发的函数
const createNamespace = ()=>{
  // 1. 先把dailog配置参数设置为true展示出来
  createNamespaceDialog.value=true
}

// submitCreateName
const submitCreateName= ()=>{
  loading.value =true
  console.log("创建namespace:",data.createName)
  // 调用创建接口创建资源
  createItem(data.clusterId,data.createName).then((response)=>{
    ElMessage({
      message: response.data.message,
      type: 'success',
    })
    getList(data.clusterId)
    createNamespaceDialog.value=false
    loading.value =false
    data.createName = ""
  })
}




// 使用vue组件生命周期，在组件被挂载之前执行动作
onBeforeMount(async ()=>{
  // 查询列表之前，要知道查询那个集群的节点列表
  // 1. 查询到集群列表
  // 2. 如果没有指定集群，则给一个默认值，进行获取集群列表
  // 3. 如果指定了集群，就直接查询当前的几点列表
  // 4. 切换了集群后重新获取节点列表
  // 5. 集群不可用，则不可以选

  // 获取集群列表
  await getClusterList()
  // 定义一个默认的集群
  const defaultClusterSelected = data.clusterList[0].id
  console.log("默认的集群是: ",defaultClusterSelected)

  // 获取当前请求是否携带了集群ID的参数
  const  curClusterId =route.query.clusterId  // curClusterId 有可能是空的
  data.clusterId = curClusterId?curClusterId:defaultClusterSelected

  await getList(data.clusterId)
})


// 解构data中的items数组
const {clusterList,clusterId,editItems,editName,detailItem,detailName,createName,deleteName,deleteNameConfirm} = toRefs(data)
const getListAddDialog = ()=>{
  //getUserList()
  editdialog.value=false
}
const closeDialog=()=>{
  // 关闭添加程序的窗口时 更新数据
  getClusterList()
  // 定义一个默认的集群
  const defaultClusterSelected = data.clusterList[0].id
  console.log("默认的集群是: ",defaultClusterSelected)

  // 获取当前请求是否携带了集群ID的参数
  const  curClusterId =route.query.clusterId  // curClusterId 有可能是空的
  data.clusterId = curClusterId?curClusterId:defaultClusterSelected
  getList(data.clusterId)
}
const rollback =()=>{
  getClusterList()
  // 定义一个默认的集群
  const defaultClusterSelected = data.clusterList[0].id
  console.log("默认的集群是: ",defaultClusterSelected)

  // 获取当前请求是否携带了集群ID的参数
  const  curClusterId =route.query.clusterId  // curClusterId 有可能是空的
  data.clusterId = curClusterId?curClusterId:defaultClusterSelected
  editdialog.value=false
  getList(data.clusterId)
}

// 搜索的逻辑
const filterTableData = computed(() =>
    data.items.filter(
        (item) =>
            !search.value ||
            item.metadata.name.toLowerCase().includes(search.value.toLowerCase())
    )
)

</script>

<template>
  <el-card element-loading-text="玩命加载中..." class="box-card">
    <template #header>
      <div class="card-header">
        <div>
          <span>namespace列表</span>
        </div>
        <div class="card-header">
<!--          <cluster-namespace-selector :show-namespace="true"></cluster-namespace-selector>-->
<!--          <ClusterNamespaceSelector @namespaceChangedRollback="getList"></ClusterNamespaceSelector>-->
          <el-select  v-model="clusterId" placeholder="选择集群ID"  @change="getList(clusterId)" style="width:200px" >
            <el-option
                v-for="item in clusterList"
                :key="item.id"
                :label="item.id"
                :value="item.id"
                :disabled="item.status === 'InActive'"
            />
          </el-select>
          <el-input v-model="search" size="small" placeholder="搜索"  style="width:200px;height: 32px; margin-left: 20px"/>
          <el-button type="primary" style="margin-left: 10px"  @click="createNamespace">创建</el-button>
        </div>
      </div>
    </template>
    <!--  放真实数据的地方  -->
    <el-table
        border
        height="480"
        :data="filterTableData"
        style="width: 100%"
    >
      <!--  align="center" 表格中居中  sortable 排序    -->
      <el-table-column fixed  prop="" align="center"  label="名称" >
        <!--   router-link 实现在点击集群id的时候路径跳转     -->
        <template #default="scope">
          <el-button link type="warning" size="small" @click="detail(scope.row)">{{ scope.row.metadata.name }}</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="metadata.creationTimestamp" align="center"  label="创建时间" sortable />
      <el-table-column prop="" align="center"  label="状态" width="200" sortable >
        <template #default="scope">
          <el-icon v-if ="scope.row.status.phase === 'Active'" style="color: green">Active</el-icon>
          <el-icon v-else style="color: red">{{scope.row.status.phase}}</el-icon>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center"  label="操作" >
        <!--  插槽的 scope 可以绑定行的数据  scope.row 获取一行的数据    -->
        <template #default="scope">
          <el-button link type="primary" size="small" @click="edit(scope.row)">资源复制</el-button>
          <el-button link type="primary" size="small" @click="edit(scope.row)">编辑</el-button>
          <el-button link type="warning" size="small" @click="deleteNamespace(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 尾部的布局 -->
    <div class="auto-space-between" style="margin-top: 15px">
      <!--      // 批量操作-->
      <div> </div>
      <!--      // 统计总数-->
      <div>总数: {{ filterTableData.length }}</div>
    </div>
  </el-card>
  <!-- 编辑namespace -->
  <el-dialog
      destroy-on-close
      @close="closeDialog()"
      v-model="editdialog"
      :title="'正在编辑集群:' + clusterId + ' namespace:' + editName"
      width="70%" >
    <Edit @rollback="getList" :cluster-id="data.clusterId"  :item-form="editItems"></Edit>
  </el-dialog>
  <!-- 详情 -->
  <el-dialog
      destroy-on-close
      v-model="detailDialog"
      :title="'集群:' + clusterId + ' 节点: ' + detailName"
      width="70%" >
    <Detail :item="detailItem"></Detail>
    <!--    <Edit @rollback="getList" :cluster-id="data.clusterId"  :item-form="editItems"></Edit>-->
    <!--    <Add :item-form="itemForm" :method="defaultMethod"  @rollback="rollback()"></Add>-->
  </el-dialog>
    <!--  创建namespace-->
  <el-dialog
      destroy-on-close
      v-model="createNamespaceDialog"
      title="创建namespace"
      width="30%" >
      <el-input v-model.trim="createName" placeholder="请输入namespace的名称"/>
      <el-button style="margin-top: 15px" type="primary"  @click="submitCreateName">创建</el-button>
  </el-dialog>
  <!--  删除namespace  -->
  <el-dialog
      destroy-on-close
      v-model="deleteNamespaceDialog"
      :title="'删除namespace: ' + deleteName"
      width="30%" >
    <el-input v-model.trim="deleteNameConfirm" placeholder="请确认删除namespace的名称"/>
    <el-button style="margin-top: 15px" type="warning"  @click="submitDeleteName">确定删除</el-button>
  </el-dialog>
</template>

<style scoped>
.card-header{
  display: flex;
  justify-content: space-between;
  align-items: center;

}
.text {
  font-size: 14px;
}
.item {
  margin-bottom: 18px;
}
</style>